package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"tech-service/pkg/logbase"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// User 示例模型
type User struct {
	ID        uint   `gorm:"primaryKey"`
	Name      string `gorm:"size:50;not null"`
	Email     string `gorm:"size:100;uniqueIndex"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

func main() {
	fmt.Println("==================================================")
	fmt.Println("           MySQL日志格式化示例")
	fmt.Println("==================================================")

	// 创建自定义MySQL日志适配器
	gormLogger := logbase.NewMySQLLogger(
		logbase.WithLogLevel(logbase.InfoLevel),         // 设置日志级别
		logbase.WithSlowThreshold(100*time.Millisecond), // 设置慢查询阈值
		logbase.WithColors(true),                        // 启用颜色输出
		logbase.WithWriter(os.Stdout),                   // 输出到标准输出
	)

	// 使用不同级别的日志
	ctx := context.Background()
	fmt.Println("\n----- 基本日志输出测试 -----")
	time.Sleep(100 * time.Millisecond) // 确保上一个输出完成

	gormLogger.Info(ctx, "这是一条 %s 消息", "INFO")
	time.Sleep(100 * time.Millisecond)

	gormLogger.Warn(ctx, "这是一条 %s 消息", "WARN")
	time.Sleep(100 * time.Millisecond)

	gormLogger.Error(ctx, "这是一条 %s 消息", "ERROR")
	time.Sleep(100 * time.Millisecond)

	// 模拟SQL日志输出
	fmt.Println("\n----- SQL查询日志测试 -----")
	time.Sleep(100 * time.Millisecond)

	// 正常查询
	startTime := time.Now().Add(-30 * time.Millisecond) // 模拟短时间查询
	gormLogger.Trace(ctx, startTime, func() (string, int64) {
		return "SELECT * FROM users WHERE status = 'active'", 10
	}, nil)
	time.Sleep(100 * time.Millisecond)

	// 慢查询
	startTime = time.Now().Add(-150 * time.Millisecond) // 模拟慢查询
	gormLogger.Trace(ctx, startTime, func() (string, int64) {
		return "SELECT * FROM orders INNER JOIN order_items ON orders.id = order_items.order_id WHERE orders.created_at > '2023-01-01'", 5
	}, nil)
	time.Sleep(100 * time.Millisecond)

	// 错误查询
	startTime = time.Now().Add(-20 * time.Millisecond)
	gormLogger.Trace(ctx, startTime, func() (string, int64) {
		return "SELECT * FROM non_existent_table WHERE id = 1", 0
	}, fmt.Errorf("ERROR 1146 (42S02): Table 'database.non_existent_table' doesn't exist"))
	time.Sleep(100 * time.Millisecond)

	// 测试无颜色模式
	fmt.Println("\n----- 无颜色模式测试 -----")
	time.Sleep(100 * time.Millisecond)

	noColorLogger := logbase.NewMySQLLogger(
		logbase.WithLogLevel(logbase.InfoLevel),
		logbase.WithSlowThreshold(100*time.Millisecond),
		logbase.WithColors(false), // 禁用颜色
		logbase.WithWriter(os.Stdout),
	)

	startTime = time.Now().Add(-50 * time.Millisecond)
	noColorLogger.Trace(ctx, startTime, func() (string, int64) {
		return "SELECT id, name, email FROM users WHERE id = 1", 1
	}, nil)
	time.Sleep(100 * time.Millisecond)

	// GORM集成测试
	fmt.Println("\n----- GORM集成测试 (DryRun模式) -----")
	time.Sleep(100 * time.Millisecond)

	// 使用DryRun模式，不需要真实的数据库连接
	db, err := gorm.Open(mysql.Open("user:pass@tcp(localhost:3306)/dbname"), &gorm.Config{
		Logger: gormLogger,
		DryRun: true, // 仅生成SQL而不执行
	})

	if err != nil {
		fmt.Printf("初始化GORM失败: %v\n", err)
	} else {
		// 创建用户
		user := User{
			Name:  "张三",
			Email: "zhangsan@example.com",
		}
		db.Create(&user)
		time.Sleep(100 * time.Millisecond)

		// 查询用户
		var users []User
		db.Where("name LIKE ?", "%张%").Find(&users)
		time.Sleep(100 * time.Millisecond)
	}

	fmt.Println("\n==================================================")
	fmt.Println("                  测试完成")
	fmt.Println("==================================================")
}
